<!-- 添加或者从新编辑税收信息 -->
<template>
	<a-modal ref="form" v-bind="options" class="add-or-upd">
		<div class="tax-information-box" name="invOrgId">
			<a-select
				ref="select"
				:disabled="props.taxId !== ''"
				style="width: 220px"
				v-model:value="formData.invOrgName"
				placeholder="开票主体"
				:options="selectOptions"></a-select>
			<a-button size="small" type="primary" @click="visibles.selectType = true">选择费用类型</a-button>
		</div>

		<a-form ref="formRef" class="house-form-base" :model="tableData">
			<vxe-table
				border
				show-overflow
				ref="grid"
				height="auto"
				:span-method="mergeRowMethod"
				:data="tableData.tableList"
				v-bind="gridOptions">
				<vxe-column field="feeSubjectName" title="费用类型" align="center"></vxe-column>
				<vxe-column field="taxationType" title="计税方式" align="center">
					<template #default="{row, rowIndex}">
						<span>{{ String(rowIndex / 2).indexOf('.') > -1 ? '个人' : '企业' }}</span>
					</template>
				</vxe-column>
				<vxe-column field="taxationPattern" align="center">
					<template #header>计税模式</template>
					<template #default="{row, rowIndex}">
						<a-form-item class="finance-form" :name="['tableList', rowIndex, 'taxationPattern']">
							<a-select v-model:value="row.taxationPattern" placeholder="计税模式" :options="orientationList" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column field="taxRate" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						税率(%)
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item
							class="finance-form"
							:name="['tableList', rowIndex, 'taxRate']"
							:rules="[
								{
									validator: passTaxRate
								}
							]">
							<a-input-number :min="0" :max="999" v-model:value="row.taxRate" placeholder="请输入税率" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column field="taxClassificationCode" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						税收分类编码
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item
							class="finance-form"
							:name="['tableList', rowIndex, 'taxClassificationCode']"
							:rules="[
								{
									validator: passTaxClassificationCode
								}
							]">
							<a-input
								v-model:value.trim="row.taxClassificationCode"
								:min="3"
								:maxlength="19"
								placeholder="请输入税收分类编码" />
						</a-form-item>
					</template>
				</vxe-column>
				<vxe-column field="preferentialPolicyType" align="center">
					<template #header>
						<a-typography-text type="danger">*</a-typography-text>
						优惠政策
					</template>
					<template #default="{row, rowIndex}">
						<a-form-item
							class="finance-form"
							:name="['tableList', rowIndex, 'preferentialPolicyType']"
							prop="preferentialPolicyType">
							<a-select v-model:value="row.preferentialPolicyType" placeholder="无优惠" :options="favouredPolicyList" />
						</a-form-item>
					</template>
				</vxe-column>
			</vxe-table>
		</a-form>
		<template #footer>
			<a-button @click="cancel">取消</a-button>
			<a-button type="primary" :loading="loading" @click="submit">确认</a-button>
		</template>
	</a-modal>

	<select-expense-type
		@checkData="getExpenseType"
		:taxId="props.taxId"
		:checkList="tableData.checkList"
		:data="tableData.noCheckList"
		v-model:visible="visibles.selectType"
		@close="visibles.selectType = false"></select-expense-type>
</template>

<script setup lang="ts">
	import {reactive, ref, toRef, defineEmits, watch, onMounted} from 'vue'
	import {VxeTablePropTypes, VxeGridProps} from 'vxe-table'
	import {SelectTypes} from 'ant-design-vue/es/select'
	import {message} from 'ant-design-vue'
	import SelectExpenseType from '@/components/finance/invoice-administration/view-taxes/select-expense-type/index.vue'
	import {getInvoicingSubjectList, addTaxRateData, updateTaxRate, getTaxRateDetails} from '@/api/tax-rate-list'
	import XEUtils from 'xe-utils'
	import {orientationList, favouredPolicyList} from '@/utils/billing-history-status'

	const props = defineProps<{
		visible: boolean
		taxId: string
	}>()
	const loading = ref(false)
	interface updateData {
		invOrgName?: string | undefined
		invOrgId: string | undefined
		taxationItems: any
	}
	const formRef = ref()

	const formData = reactive<updateData>({
		invOrgId: undefined,
		invOrgName: undefined,
		taxationItems: []
	})

	const passTaxClassificationCode = (rule: any, value: string) => {
		if (value === '') {
			tableData.tableList.forEach((e, index) => {
				if (index + 1 < tableData.tableList.length) {
					if (e.feeSubjectId == tableData.tableList[index + 1].feeSubjectId) {
						// if (e.taxRate !== null || e.taxClassificationCode.length >= 3 || tableData.tableList[index + 1].taxRate !== null || tableData.tableList[index + 1].taxClassificationCode.length >= 3) {
						// 	if (e.taxRate !== '' && e.taxRate !== null && e.taxClassificationCode && e.taxClassificationCode.length >= 3) {
						// 		e.temp = true
						// 		console.log(e, 'passTaxClassificationCode---true')
						// 	} else {
						// 		e.temp = false
						// 		console.log(e, 'passTaxClassificationCode---false')
						// 	}
						// 	if (tableData.tableList[index + 1].taxRate !== '' && tableData.tableList[index + 1].taxRate !== null && tableData.tableList[index + 1].taxClassificationCode && tableData.tableList[index + 1].taxClassificationCode.length >= 3) {
						// 		tableData.tableList[index + 1].temp = true
						// 		console.log(tableData.tableList[index + 1], 'passTaxClassificationCode---true')
						// 	} else {
						// 		tableData.tableList[index + 1].temp = false
						// 		console.log(tableData.tableList[index + 1], 'passTaxClassificationCode----false')
						// 	}
						// } else {
						// }
						if (
							(e.taxRate !== '' && e.taxRate !== null && e.taxClassificationCode.length >= 3) ||
							(tableData.tableList[index + 1].taxRate !== '' &&
								tableData.tableList[index + 1].taxRate !== null &&
								tableData.tableList[index + 1].taxClassificationCode.length >= 3)
						) {
							// return (temp.value = true)
							if (e.taxRate !== '' && e.taxRate !== null && e.taxClassificationCode.length >= 3) {
								e.temp = true
							} else if (e.taxRate === null && e.taxClassificationCode === '') {
								e.temp = true
							} else {
								e.temp = false
							}

							if (
								tableData.tableList[index + 1].taxRate !== '' &&
								tableData.tableList[index + 1].taxRate !== null &&
								tableData.tableList[index + 1].taxClassificationCode.length >= 3
							) {
								tableData.tableList[index + 1].temp = true
							} else if (
								tableData.tableList[index + 1].taxRate === null &&
								tableData.tableList[index + 1].taxClassificationCode == ''
							) {
								tableData.tableList[index + 1].temp = true
							} else {
								tableData.tableList[index + 1].temp = false
							}
							// if ((tableData.tableList[index + 1].taxRate !== '' && tableData.tableList[index + 1].taxRate !== null && tableData.tableList[index + 1].taxClassificationCode.length >= 3) || (tableData.tableList[index + 1].taxRate === null && tableData.tableList[index + 1].taxClassificationCode === '')) {
							// 	tableData.tableList[index + 1].temp = true
							// }
						} else {
							e.temp = false
							tableData.tableList[index + 1].temp = false
							// return (temp.value = false)
						}
					}
				}
			})
			console.log(tableData.tableList, 157)
			if (tableData.tableList.every((e: any) => e.temp)) {
				return Promise.resolve()
			} else {
				return Promise.reject()
			}
		} else if (value?.length < 3) {
			return Promise.reject()
		} else {
			return Promise.resolve()
		}
	}
	const passTaxRate = (rule: any, value: string) => {
		console.log(value)
		if (String(value).indexOf('.') > -1 || value === null) {
			if (String(value).indexOf('.') > -1) {
				return Promise.reject('税率格式不正确')
			} else {
				tableData.tableList.forEach((e, index) => {
					if (index + 1 < tableData.tableList.length) {
						if (e.feeSubjectId == tableData.tableList[index + 1].feeSubjectId) {
							if (
								(e.taxRate !== '' && e.taxRate !== null && e.taxClassificationCode.length >= 3) ||
								(tableData.tableList[index + 1].taxRate !== '' &&
									tableData.tableList[index + 1].taxRate !== null &&
									tableData.tableList[index + 1].taxClassificationCode.length >= 3)
							) {
								// return (temp.value = true)

								if (e.taxRate !== '' && e.taxRate !== null && e.taxClassificationCode.length >= 3) {
									e.temp = true
								} else if (e.taxRate === null && e.taxClassificationCode == '') {
									e.temp = true
								} else {
									e.temp = false
								}

								if (
									tableData.tableList[index + 1].taxRate !== '' &&
									tableData.tableList[index + 1].taxRate !== null &&
									tableData.tableList[index + 1].taxClassificationCode.length >= 3
								) {
									tableData.tableList[index + 1].temp = true
								} else if (
									tableData.tableList[index + 1].taxRate === null &&
									tableData.tableList[index + 1].taxClassificationCode == ''
								) {
									tableData.tableList[index + 1].temp = true
								} else {
									tableData.tableList[index + 1].temp = false
								}
							} else {
								e.temp = false
								tableData.tableList[index + 1].temp = false
							}
						}
					}
				})
				console.log(tableData.tableList, '212')
				if (tableData.tableList.every((e: any) => e.temp)) {
					return Promise.resolve()
				} else {
					return Promise.reject()
				}
			}
		} else {
			return Promise.resolve()
		}
	}
	const emits = defineEmits(['update:visible', 'close'])
	const grid = ref()

	const options = reactive({
		title: '税收信息',
		width: 1300,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		confirmLoading: false,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const submit = () => {
		formRef.value.validate().then(() => {
			if (props.taxId === '') {
				formData.invOrgId = formData.invOrgName
			}
			if (formData.invOrgId === '' || formData.invOrgId === undefined) {
				message.error('开票主体不能为空')
				return
			}
			if (tableData.tableList.length === 0) {
				message.error('请选择费用类型')
				return
			}
			formData.taxationItems = tableData.tableList.filter(e => {
				if (e.taxRate !== null && e.taxRate !== '') {
					e.taxRate = e.taxRate / 100
				}
				return e.taxClassificationCode && e.taxRate !== null && e.taxRate !== ''
			})
			loading.value = true
			delete formData.invOrgName
			if (!props.taxId) {
				// 新增
				return addTaxRateData(formData)
					.then(() => {
						loading.value = false
						message.success('税收信息保存成功，可以进行开票。')
						emits('close')
					})
					.catch(error => (loading.value = false))
			} else {
				// 更新
				return updateTaxRate(formData)
					.then(() => {
						loading.value = false
						message.success('税收信息保存成功，可以进行开票。')
						emits('close')
					})
					.catch(error => (loading.value = false))
			}
		})
	}

	const cancel = () => {
		emits('update:visible', false)
		setTimeout(() => emits('close'), 100)
	}

	const selectOptions = ref<SelectTypes['options']>([])

	/* 表格的数据 */
	const tableData = reactive<any>({
		tableList: [],
		noCheckList: [],
		checkList: []
	})

	const list = ref([])

	const visibles = reactive({
		selectType: false
	})

	/**
	 * 单元格配置
	 */
	const gridOptions = reactive<VxeGridProps>({
		rowConfig: {
			isHover: true,
			height: 60
		}
	})

	/**
	 * 计算单元格合并
	 */

	const mergeRowMethod: VxeTablePropTypes.SpanMethod = ({row, _rowIndex, column, visibleData}) => {
		const fields = ['feeSubjectName']
		const cellValue = row[column.field]
		if (cellValue && fields.includes(column.field)) {
			const prevRow = visibleData[_rowIndex - 1]
			let nextRow = visibleData[_rowIndex + 1]
			if (prevRow && prevRow[column.field] === cellValue) {
				return {rowspan: 0, colspan: 0}
			} else {
				let countRowspan = 1
				while (nextRow && nextRow[column.field] === cellValue) {
					nextRow = visibleData[++countRowspan + _rowIndex]
				}
				if (countRowspan > 1) {
					return {rowspan: countRowspan, colspan: 1}
				}
			}
		}
	}

	// 搜索
	const search = (page?: number) => {
		setTimeout(() => grid.value?.commitProxy(page === 1 ? 'reload' : 'query'), page ? 0 : 500)
	}
	onMounted(() => {
		if (!props.taxId) {
			// 新增
			getInvoicingSubjectList({hasTaxation: false}).then(res => {
				selectOptions.value = res.data.map(e => {
					return {
						...e,
						label: e.name,
						value: e.id
					}
				})
			})
		}
	})

	/**
	 *获取费用类型
	 */
	const getExpenseType = (checkData: any, noCheck: any) => {
		list.value = XEUtils.clone(checkData, true)
		tableData.noCheckList = XEUtils.clone(noCheck, true)
		checkData.forEach((e: any) => {
			if (tableData.tableList.findIndex((o: any) => e.id === o.feeSubjectId) === -1) {
				tableData.tableList.push({
					feeSubjectName: e.name,
					feeSubjectId: e.id,
					id: '',
					preferentialPolicyType: 0,
					taxClassificationCode: '',
					taxRate: null,
					taxationPattern: 2,
					taxationType: 1
				})
				tableData.tableList.push({
					feeSubjectName: e.name,
					feeSubjectId: e.id,
					id: '',
					preferentialPolicyType: 0,
					taxClassificationCode: '',
					taxRate: null,
					taxationPattern: 2,
					taxationType: 2
				})
			}
		})
		tableData.tableList = tableData.tableList.filter((e: any) => checkData.some((o: any) => e.feeSubjectId === o.id))
		tableData.checkList = tableData.tableList.map((e: any) => {
			return {
				id: e.feeSubjectId,
				name: e.feeSubjectName
			}
		})
	}
	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				formData.invOrgName = undefined
				formData.invOrgId = undefined
				formData.taxationItems = []
				tableData.noCheckList = []
				tableData.tableList = []
			}
			if (props.taxId) {
				getDetails()
			}
		}
	)

	/**
	 * 获取详情数据
	 */
	const getDetails = () => {
		getTaxRateDetails(props.taxId).then(res => {
			formData.invOrgId = res.data.invOrgId
			formData.invOrgName = res.data.invOrgName
			res.data.taxationItems.forEach((e, index) => {
				tableData.tableList.push({
					...e,
					taxRate: Math.floor(e.taxRate * 100)
				})
				if (getCount(res.data.taxationItems, e) !== 2) {
					if (e.taxationType === 1) {
						tableData.tableList.push({
							feeSubjectName: e.feeSubjectName,
							feeSubjectId: e.feeSubjectId,
							preferentialPolicyType: 0,
							taxClassificationCode: '',
							taxRate: null,
							taxationPattern: 2,
							taxationType: 2
						})
					} else if (e.taxationType === 2) {
						tableData.tableList.push({
							feeSubjectName: e.feeSubjectName,
							feeSubjectId: e.feeSubjectId,
							preferentialPolicyType: 0,
							taxClassificationCode: '',
							taxRate: null,
							taxationPattern: 2,
							taxationType: 1
						})
					}
				}
			})

			tableData.checkList = res.data.taxationItems.map(e => {
				return {
					id: e.feeSubjectId,
					name: e.feeSubjectName
				}
			})
		})
	}

	//计算出现次数
	const getCount = (arr, num) => {
		var i = 0
		arr.forEach(ele => {
			ele.feeSubjectId === num.feeSubjectId ? i++ : ''
		})
		return i
	}
</script>

<style lang="less">
	.add-or-upd {
		.ant-modal-body {
			height: 80vh;
			overflow: auto;
		}
		.bill-add-dialog {
			padding: 8px 10px;
		}
		.tax-information-box {
			display: flex;
			justify-content: space-between;
			margin-bottom: 10px;
		}
		.house-form-base {
			height: 90%;
			// .finance-form {
			// 	margin: ;
			// }
		}
	}
</style>
